import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

import 'package:image_cropper/image_cropper.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

final List<File> imageList = [];
// 使用ImagePicker前必须先实例化
final ImagePicker imagePicker = ImagePicker();

class ImageWidget extends StatefulWidget {
  const ImageWidget({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ImageWidget();
  }
}

class _ImageWidget extends State<ImageWidget> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
        title: const Text("图片"),
        centerTitle: true,
        toolbarHeight: 50,
        backgroundColor: Colors.white,
        titleTextStyle: const TextStyle(color: Colors.blue),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          TextButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all<Color>(Colors.blue),
              foregroundColor: MaterialStateProperty.resolveWith((states) {
                if (states.contains(MaterialState.focused)) {
                  return Colors.white;
                } else if (states.contains(MaterialState.pressed)) {
                  return Colors.red;
                }
              }),
            ),
            onPressed: () {
              singleImage(ImageSource.camera);
            },
            child: const Text("拍照"),
          ),
          TextButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all<Color>(Colors.blue),
              foregroundColor: MaterialStateProperty.resolveWith((states) {
                if (states.contains(MaterialState.focused)) {
                  return Colors.white;
                } else if (states.contains(MaterialState.pressed)) {
                  return Colors.red;
                }
              }),
            ),
            onPressed: () {
              singleImage(ImageSource.gallery);
            },
            child: const Text("选择照片--单选"),
          ),
          TextButton(
            style: ButtonStyle(
              backgroundColor: MaterialStateProperty.all<Color>(Colors.blue),
              foregroundColor: MaterialStateProperty.resolveWith((states) {
                if (states.contains(MaterialState.focused)) {
                  return Colors.white;
                } else if (states.contains(MaterialState.pressed)) {
                  return Colors.red;
                }
              }),
            ),
            onPressed: () {
              multiImage();
            },
            child: const Text("选择照片--多选"),
          ),
          getList(),
        ],
      ),
    );
  }

  Widget getList() {
    return Expanded(
      child: ListView.builder(
        shrinkWrap: false,
        // physics: const NeverScrollableScrollPhysics(),
        itemCount: imageList.length,
        itemBuilder: (context, index) {
          return GestureDetector(
            child: Image.file(
              imageList[index],
              width: 60,
              height: 60,
              // fit: BoxFit.cover,
            ),
          );
        },
      ),
    );
  }

  singleImage(imageSource) async {
    List<AssetEntity>? result = await AssetPicker.pickAssets(context,useRootNavigator:true);
    File? file;
    if (null != result && result.isNotEmpty) {
      file =await  result[0].file;
      imageList.clear();
    }

    // XFile? image = await imagePicker.pickImage(source: imageSource);
    // if (null != image) {
    //   cropImage(image.path);
    // }
    setState(() {
      if (null != file) {
        imageList.add(file);
      }
    });
  }

  multiImage() async {
    List<XFile>? images = await imagePicker.pickMultiImage();
    setState(() {
      imageList.clear();
      if (null != images && images.isNotEmpty) {
        for (var i = 0; i < images.length; i++) {
          imageList.add(File(images[i].path));
        }
      }
    });
  }

  cropImage(path) async {
    CroppedFile? croppedFile = await ImageCropper().cropImage(
        sourcePath: path,
        compressQuality: 100,
        // cropStyle: CropStyle.circle,
        aspectRatioPresets: Platform.isAndroid
            ? [
                CropAspectRatioPreset.square,
                CropAspectRatioPreset.ratio3x2,
                CropAspectRatioPreset.original,
                CropAspectRatioPreset.ratio4x3,
                CropAspectRatioPreset.ratio16x9
              ]
            : [
                CropAspectRatioPreset.original,
                CropAspectRatioPreset.square,
                CropAspectRatioPreset.ratio3x2,
                CropAspectRatioPreset.ratio4x3,
                CropAspectRatioPreset.ratio5x3,
                CropAspectRatioPreset.ratio5x4,
                CropAspectRatioPreset.ratio7x5,
                CropAspectRatioPreset.ratio16x9
              ],
        uiSettings: [
          AndroidUiSettings(
            toolbarTitle: 'Cropper',
            toolbarColor: Colors.deepOrange,
            toolbarWidgetColor: Colors.white,
            initAspectRatio: CropAspectRatioPreset.original,
            //缩放框是否可以拖动 true为不可拖动
            lockAspectRatio: true,
            //是否显示底部控制区域 true为不显示
            hideBottomControls: false,
            //网格列数
            cropGridColumnCount: 10,
            //是否显示网格 true 为显示
            showCropGrid: true,
          ),
          IOSUiSettings(
            title: 'Cropper',
          )
        ]);
    setState(() {
      if (croppedFile != null) {
        imageList.clear();
        imageList.add(File(croppedFile.path));
      }
    });
  }

// Future<void> retrieveLostData() async {
//   LostDataResponse? response = await imagePicker.retrieveLostData();
//   if (response == null) {
//     return;
//   }
//   if (response.file != null) {
//     setState(() {
//       if (response.type == RetrieveType.video) {
//         _handleVideo(response.file);
//       } else {
//         _handleImage(response.file);
//       }
//     });
//   } else {
//     _handleError(response.exception);
//   }
// }
}
